package com.xuxin.baby.activity;

import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;

import androidx.annotation.NonNull;

import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.EncryptUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.RegexUtils;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.xuxin.baby.R;
import com.xuxin.baby.base.BaseActivity;
import com.xuxin.baby.base.BaseConstant;
import com.xuxin.baby.bean.AuthenticateBean;
import com.xuxin.baby.bean.BaseBean;
import com.xuxin.baby.bean.LoginBean;
import com.xuxin.baby.bean.TenantIdBean;
import com.xuxin.baby.contract.LoginContract;
import com.xuxin.baby.presenter.LoginPresenter;
import com.xuxin.baby.utils.ACache;
import com.xuxin.baby.view.CountDown;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by xu_xin
 * Created on 2020.08.19 0019
 * 验证码登录
 * 登录分三步
 * 1.租户接口
 * 2.API授权
 * 3.登录(未注册自动注册登录)
 */
public class LoginActivity extends BaseActivity implements LoginContract.View {
    private final LoginContract.Presenter presenter = new LoginPresenter(this);
    @BindView(R.id.login_phone)
    EditText login_phone;
    @BindView(R.id.login_code)
    EditText login_code;
    @BindView(R.id.login_send)
    CountDown login_send;
    @BindView(R.id.login_agree)
    CheckBox login_agree;

    private ACache aCache;
    private String tenantId;//租户id
    private String token;//授权token
    private String phone;//手机号

    @Override
    public void setContentView() {
        setContentView(R.layout.activity_login);
    }

    @Override
    public void initView() {

    }

    @Override
    public void initData() {
        aCache = ACache.get(context);
    }

    @Override
    public void onComplete() {
        dismiss();
    }

    @Override
    @OnClick({R.id.login_send, R.id.login_on})
    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.login_send) {
            phone = login_phone.getText().toString().trim();
            if (!RegexUtils.isMobileExact(phone)) {
                ToastUtils.showShort("请输入正确的手机号码");
            } else if (!login_send.startTimer()) {
                ToastUtils.showShort("时间还没到呢");
            } else {
                Message message = Message.obtain();
                message.what = 0;
                message.obj = getCodeMessage(phone);
                handler.sendMessage(message);
            }
        } else if (id == R.id.login_on) {
            phone = login_phone.getText().toString().trim();
            String inputCode = login_code.getText().toString();
            String loginAuthPhone = aCache.getAsString("loginAuthPhone");
            String loginAuthCode = aCache.getAsString("loginAuthCode");
            LogUtils.e("phone = " + phone);
            LogUtils.e("loginAuthCode = " + loginAuthCode);
            LogUtils.e("inputCode = " + inputCode);
            if (!login_agree.isChecked()) {
                ToastUtils.showShort("请先同意《用户协议》和《隐私协议》");
            } else if (!RegexUtils.isMobileExact(phone) || !phone.equals(loginAuthPhone)) {
                ToastUtils.showShort("请输入正确的手机号码");
            } else if (StringUtils.isEmpty(loginAuthCode)) {
                ToastUtils.showShort("验证码已过期");
            } else if (!inputCode.equals(loginAuthCode)) {
                ToastUtils.showShort("动态密码错误");
            } else {
                try {
                    popup.setTitle("正在授权中...").show();
                    handler.sendEmptyMessage(1);
                } catch (Exception e) {
                    e.printStackTrace();
                    dismiss();
                }
            }
        }
    }

    private final Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(@NonNull Message msg) {
            switch (msg.what) {
                case 0://发送验证码
                    //presenter.sendCode(phone, code);
                    login_code.setText((String) msg.obj);
                    break;
                case 1://租户接口
                    presenter.getTenantId(BaseConstant.tenancyName);
                    break;
                case 2://API授权
                    presenter.authenticate(tenantId, BaseConstant.userNameOrEmailAddress, BaseConstant.password);
                    break;
                case 3://登录(未注册自动注册登录)
                    presenter.login(tenantId, token, phone);
                    break;
                case 4://查询授权用户信息
                    presenter.getInfo(tenantId, token);
                    break;
            }
            return false;
        }
    });

    @Override
    public void onSuccess(TenantIdBean tenantIdBean) {
        if (null != tenantIdBean.getResult()) {
            tenantId = tenantIdBean.getResult().getTenantId();
            handler.sendEmptyMessage(2);
        }
    }

    @Override
    public void onSuccess(AuthenticateBean authenticateBean) {
        if (null != authenticateBean.getResult()) {
            popup.setTitle("正在登录中...");
            token = authenticateBean.getResult().getAccessToken();
            handler.sendEmptyMessage(3);
        }
    }

    @Override
    public void onSuccess(BaseBean baseBean) {
        ToastUtils.showShort(baseBean.getError().getMessage());
    }

    @Override
    public void onSuccess(LoginBean loginBean) {
        if (null != loginBean.getResult()) {
            ACache aCache = ACache.get(this);
            aCache.put(BaseConstant.memberId, loginBean.getResult().getId());
            aCache.put(BaseConstant.tenantId, tenantId);
            aCache.put(BaseConstant.token, "bearer " + token);
            if (loginBean.getResult().getChildrenNum() > 0) {
                aCache.put(BaseConstant.login, true);
                ActivityUtils.startActivity(MainActivity.class);
            } else {
                ActivityUtils.startActivity(LoginGuideActivity.class);
            }
            finish();
        }
    }

    /**
     * 验证码
     */
    private String getCodeMessage(String phone) {
        String time = phone + System.currentTimeMillis();
        String md5 = EncryptUtils.encryptMD5ToString(time);
        String loginAuthCode = md5.substring(md5.length() - 6);
        aCache.put("loginAuthPhone", phone);
        aCache.put("loginAuthCode", loginAuthCode, ACache.time_minutes);
        LogUtils.e("getCodeMessage = " + loginAuthCode);
        return loginAuthCode;
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        LogUtils.e("onNewIntent");
    }
}